package module

import (
	"lambda"
	"bridge/base"
	"bridge/list"
)

type Module struct {
	Body lambda.Term
	Deps []string
}

func FromTerm(term lambda.Term, env lambda.Environment) Module {
	var body_term, deps_term lambda.Term

	body_term, term = list.Split(term)
	deps_term, term = list.Split(term)

	deps_bytes := list.ReducePrimitiveList(deps_term, env)

	deps := make([]string, len(deps_bytes))
	for i, bytes := range deps_bytes {
		deps[i] = string([]byte(bytes))
	}

	return Module{body_term, deps}
}

func (module Module) ToTerm() lambda.Term {
	deps := list.Empty()
	for i := len(module.Deps) - 1; i >= 0; i-- {
		deps = list.PushFront(base.PrimString(module.Deps[i]), deps)
	}

	mod := list.Empty()
	mod = list.PushFront(deps, mod)
	mod = list.PushFront(module.Body, mod)

	return mod
}
